package server;

import mapper.Content;
import mapper.Host;
import mapper.Mapper;
import mapper.Wrapper;

import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.List;
import java.util.Map;

public class RequestProcessorNew extends Thread {

    private Socket socket;
    private Mapper mapper;
    public RequestProcessorNew(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String url=request.getUrl();
            // 静态资源处理
            List<Host> hostList = mapper.getHostList();
            boolean bo=false;
            for (Host host : hostList) {
                if(host.getName().equalsIgnoreCase(request.getHostName())){
                    List<Content> list = host.getList();
                    for (Content content : list) {
                        List<Wrapper> listWarpper = content.getList();
                        for (Wrapper wrapper : listWarpper) {
                            if(url.equalsIgnoreCase(wrapper.getPath())){
                                bo=true;
                                HttpServlet httpServlet = wrapper.getHttpServlet();
                                httpServlet.service(request,response);
                            }
                        }
                    }

                }

            }
            if(!bo){
                response.outputHtml(request.getUrl());
            }
          /*  if(servletMap.get(request.getUrl()) == null) {
                response.outputHtml(request.getUrl());
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = servletMap.get(request.getUrl());
                httpServlet.service(request,response);
            }*/

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
